import React, { Component } from 'react'
import axios from './../../axios'
import Utils from './../../utils/utils'
import ETable from './../../components/ETable'
import BaseForm from './../../components/BaseForm'
import { Card, Button, Modal, Form, Input, Radio, DatePicker, Select } from 'antd'
import RadioGroup from 'antd/lib/radio/group'
import Moment from 'moment'
const FormItem = Form.Item;
const TextArea = Input.TextArea;
const { Option } = Select;

export default class User extends Component {

  // 初始化
  state = {}

  // 自定义的params，page代表的是请求数据第几页
  params = {
    page: 1
  }

  // 组件数据
  formList = [
    {
      type: 'INPUT',
      label: '用户名',
      field: 'user_name',
      placeholder: '请输入名称',
      width: 100
    },
    {
      type: 'INPUT',
      label: '手机号',
      field: 'user_mobile',
      placeholder: '请输入手机号',
      width: 120,
    },
    {
      type: 'DATE',
      label: '请选择入职日期',
      field: 'user_date',
      placeholder: '请输入日期',
      width: 100,
    },
  ]

  // 执行完dom操作后运行
  componentDidMount() {
    // 默认调用请求数据
    this.requestList();
  }

  // 默认请求我们的接口数据
  requestList = () => {
    // 调用公共封装的列表请求函数
    axios.requestList(this, '/user/list', this.params, true)
  }

  /** 
   * 员工操作函数
   * @param {String} type 输入操作的类型
  */
  hanleOperate = (type) => {
    let item = this.state.selectedItem;
    if (type == 'create') {
      this.setState({
        type,
        isVisible: true,
        title: '创建员工'
      })
    } else {
      if (!item) {
        Modal.info({
          title: '信息',
          content: '请选择一个用户'
        })
        return;
      }
      if (type == 'edit' || type == 'detail') {
        this.setState({
          type,
          isVisible: true,
          title: type == 'edit' ? '编辑用户' : '查看详情',
          userInfo: item
        })
      } else if(type == 'delete') {
        Modal.confirm({
          title: '确定要删除此用户吗？',
          onOk: () => {
            axios.ajax({
              url: '/user/delete',
              data: {
                params: {
                  id: item.id
                }
              },
              isMock: true
            }).then((res) => {
              if (res.code == 0) {
                this.setState({
                  isVisible: false
                })
                this.requestList();
              }
            })
          }
        })
      }
    }
  }

  // 员工创建提交
  handleSubmit = () => {
    this.userForm.props.form.validateFields(err => {
      if (!err) {
        let type = this.state.type;
        let data = this.userForm.props.form.getFieldsValue();
        axios.ajax({
          url: type == 'create' ? '/user/add' : '/user/edit',
          data: {
            params: data
          },
          isMock: true
        }).then(res => {
          if (res.code == 0) {
            this.setState({
              isVisible: false
            })
            this.userForm.props.form.resetFields()
            this.requestList()
          }
        })
      }
    });
  }

  // 子组件调用方法
  /**
   * 子组件点击查询
   */
  handleFilter = (params) => {
    this.params = params
    this.requestList()
  }

  render() {
    // 表格模型
    const columns = [{
      title: 'id',
      dataIndex: 'id'
    }, {
      title: '用户名',
      dataIndex: 'username'
    }, {
      title: '性别',
      dataIndex: 'sex',
      render(sex) {
        return sex == 1 ? '男' : '女'
      }
    }, {
      title: '状态',
      dataIndex: 'state',
      render(state) {
        let config = {
          '1': '咸鱼一条',
          '2': '风华浪子',
          '3': '北大才子一枚',
          '4': '百度FE',
          '5': '创业者'
        }
        return config[state];
      }
    }, {
      title: '爱好',
      dataIndex: 'interest',
      render(interest) {
        let config = {
          '1': '游泳',
          '2': '打篮球',
          '3': '踢足球',
          '4': '跑步',
          '5': '爬山',
          '6': '骑行',
          '7': '桌球',
          '8': '麦霸'
        }
        return config[interest];
      }
    }, {
      title: '爱好',
      dataIndex: 'isMarried',
      render(isMarried) {
        return isMarried ? '已婚' : '未婚'
      }
    }, {
      title: '生日',
      dataIndex: 'birthday'
    }, {
      title: '联系地址',
      dataIndex: 'address'
    }, {
      title: '早起时间',
      dataIndex: 'time'
    }
    ];

    let footer ={};
    if (this.state.type == 'detail') {
      footer ={
        footer: null
      }
    }

    return (
      <div>
        <Card>
          <BaseForm filterSubmit={ this.handleFilter } formList={ this.formList } />
        </Card>
        {/* 中间按钮操作 */ }
        <Card style={ { marginTop: 10 } } className="operate-wrap">
          <Button type="primary" style={ { marginRight: 10 } } icon="plus" onClick={ () => this.hanleOperate('create') }>创建员工</Button>
          <Button style={ { marginRight: 10 } } icon="edit" onClick={ () => this.hanleOperate('edit') }>编辑员工</Button>
          <Button style={ { marginRight: 10 } } icon="info-circle" onClick={ () => this.hanleOperate('detail') }>员工详情</Button>
          <Button type="danger" style={ { marginRight: 10 } } icon="delete" onClick={ () => this.hanleOperate('delete') }>删除员工</Button>
        </Card>
        {/* 底部表格 */ }
        <div className="content-wrap">
          <ETable
            columns={ columns }
            updateSelectedItem={ Utils.updateSelectedItem.bind(this) }
            selectedRowKeys={ this.state.selectedRowKeys }
            dataSource={ this.state.list }
            pagination={ this.state.pagination }
          />
        </div>
        <Modal
          title={ this.state.title }
          visible={ this.state.isVisible }
          onOk={ this.handleSubmit }
          onCancel={ () => {
            this.setState({
              isVisible: false,
              userInfo: null
            })
            this.userForm.props.form.resetFields()
          } }
          width={ 600 }
          { ...footer}
        >
          <UserForm userInfo={ this.state.userInfo} type={this.state.type} wrappedComponentRef={(inst)=>this.userForm = inst}></UserForm>
        </Modal>
      </div>
    )
  }
}

class UserForm extends Component {

  getState = (state) => {
    return {
      '1': '咸鱼一条',
      '2': '风华浪子',
      '3': '北大才子一枚',
      '4': '百度FE',
      '5': '创业者'
    }[state]
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const userInfo = this.props.userInfo || {};
    const type = this.props.type;
    
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 }
    }
    return (
      <Form layout="horizontal" { ...formItemLayout }>
        <FormItem label="用户名">
          {
            userInfo && type == 'detail' ? userInfo.username :getFieldDecorator('user_name', {
              initialValue: userInfo.username,
              rules: [
                {
                  required: true,
                  message: '请输入用户名',
                },
              ],
            })(
              <Input type="text" placeholder="请输入用户名" />
            )
          }
        </FormItem>
        <FormItem label="性别">
          {
            userInfo && type == 'detail' ? userInfo.sex == 1 ? '男' : '女' :getFieldDecorator('sex',{
              initialValue: userInfo.sex
            })(
              <RadioGroup>
                <Radio value={ 1 }>男</Radio>
                <Radio value={ 2 }> 女</Radio>
              </RadioGroup>
            )
          }
        </FormItem>
        <FormItem label="状态">
          {
            userInfo && type == 'detail' ? this.getState(userInfo.state) :getFieldDecorator('state',{
              initialValue: userInfo.state
            })(
              <Select style={ { width: 120 } }>
                <Option value={1}>咸鱼一条</Option>
                <Option value={2}>风华浪子</Option>
                <Option value={3}>北大才子</Option>
                <Option value={4}>百度FE</Option>
                <Option value={5}>创业者</Option>
              </Select>
            )
          }
        </FormItem>
        <FormItem label="生日">
          {
            userInfo && type == 'detail' ? userInfo.birthday : getFieldDecorator('birthday', {
              initialValue: Moment(userInfo.birthday)
            })(
              <DatePicker/>
            )
          }
        </FormItem>
        <FormItem label="联系地址">
          {
            userInfo && type == 'detail' ? userInfo.address :getFieldDecorator('address', {
              initialValue: userInfo.address,
              rules: [
                {
                  required: true,
                  message: '请输入地址信息',
                },
              ],
            })(
              <TextArea rows={3} placeholder="请输入联系地址"/>
            )
          }
        </FormItem>
      </Form>
    )
  }
}

UserForm = Form.create({})(UserForm);
